import random
from decimal import Decimal, getcontext

def generate_resources():
    # prepare the resources for the round
    # r[0] = name, r[1] = chance of occurrence, rounded to 2 sig digits]
    resources_list = [
            ['resource a', round(Decimal(0.1), 2)],
            ['resource b', round(Decimal(0.1), 2)],
            ['resource c', round(Decimal(0.2), 2)]
            ]

    resources = [ {'name': r[0],  'freq': r[1], 'lower': None, 'upper':
        None } for r in resources_list ]

    # set up the resources w/ probability distribtions, based on frequencies
    # these are non-overlapping windows, used to determine, w/ a random
    # number, which reso is on which square
    resource_freq_assign(resources, resources_list)

    return resources

# setup resource frequency distribution
def resource_freq_assign(resources, resources_list):
    for reso in resources_list:
        lower = 0
        index = resources_list.index(reso)
        if index == 0:
            for r in resources:
                if r['name'] == reso[0]:
                    r['lower'] = round(Decimal(0), 2)
                    r['upper'] = reso[1]
        else:
            for sub_reso in resources_list[0:index]:
                lower += sub_reso[1]
            for r in resources:
                if r['name'] == reso[0]:
                    r['lower'] = lower
                    r['upper'] = lower + r['freq']

# determine which reso is on each square
def select_resource(resources):
    n = random.random()
    for resource in resources:
        if n > resource['lower'] and n <= resource['upper']:
            return resource
    return None
